package com.yearner.reviewplan.user.model;


import com.yearner.reviewplan.common.exception.NormalException;
import com.yearner.reviewplan.common.util.CheckDataUtil;
import com.yearner.reviewplan.common.util.StringUtils;

import java.util.Arrays;

/**
 * @author pengyg
 * @since 2019/10/21
 */
public class Cycle {

    /**
     * 周期间隔
     */
    private Double[] cycles;

    private static long oneDayMillis = 86400000;
    /**
     * 数组最小长度 todo 用户可自由修改，后端检查是否匹配
     */
    private static final int MIN_CYCLE_LENGTH = 7;

    //--------------- 构造相关 -------------------

    private Cycle() {
        this.cycles = new Double[]{0.5, 1.0, 2.0, 7.0, 30.0, 90.0, 180.0};
    }

    public static Cycle create() {
        return new Cycle();
    }

    public static Cycle create(Double[] cyc) {
        Cycle cycle = new Cycle();
        if (cycle.cycles != null && (cycle.cycles.length >= MIN_CYCLE_LENGTH)) {
            cycle.cycles = cyc;
        }
        return cycle;
    }

    //--------------- 构造相关end -------------------


    /**
     * 修改周期间隔
     *
     * @param cycles
     */
    void changeCycles(Double[] cycles) {
        if (cycles == null || cycles.length < MIN_CYCLE_LENGTH) {
            throw new NormalException("周期 不合法!");
        } else {
            if (CheckDataUtil.haveIllegalValues((Double c) -> (c==null || c <= 0), cycles)) {
                throw new NormalException("周期 不合法!");
            }
        }
        this.cycles = cycles;
    }


    /**
     * 计算当前时间距离上次记录的时间，是否满足 当前周期间隔
     *
     * @param lastTime 上次记录的时间
     * @return
     */
    public boolean calculate(int stageIndex, long lastTime) {
        stageIndex = Math.min(stageIndex, MIN_CYCLE_LENGTH);
        long time = System.currentTimeMillis() - lastTime;
        return time >= (cycles[stageIndex] * oneDayMillis);
    }
}
